/**
 * @file BrowserWidget.cpp
 */
#include <BrowserWidget.hpp>

#include <iostream>
#include <qfiledialog.h>

#include <Utils.hpp>

BrowserWidget::BrowserWidget(QWidget* parent) :
	QWidget(parent) {
	this->_dirModel = new QDirModel();

	this->_tree = new QTreeView(this);
	this->_tree->setModel(this->_dirModel);
	this->_tree->setSelectionMode(QTreeView::ExtendedSelection);
	this->_tree->setSelectionBehavior(QTreeView::SelectRows);
	this->_tree->setColumnHidden(1, true);
	this->_tree->setColumnHidden(2, true);
	this->_tree->setColumnHidden(3, true);

	this->_path = new QLineEdit(this);

	this->_browserButton = new QPushButton(this);
	this->_browserButton->setText("&Browse");
	QObject::connect(this->_browserButton, SIGNAL(pressed()), this, SLOT(browseForDirectory()));

	this->_browser=new QFileDialog(this);
	this->_browser->setFileMode(QFileDialog::DirectoryOnly);
	this->_browser->setViewMode(QFileDialog::Detail);

	this->setDirectory(Utils::HomeDirectory());
}

BrowserWidget::~BrowserWidget() {
	delete this->_tree;
	delete this->_dirModel;
	delete this->_path;
	delete this->_browser;
	delete this->_browserButton;
}

void BrowserWidget::browseForDirectory() {
	this->_browser->setDirectory(this->_path->text());
	this->_browser->exec();
	QStringList path = this->_browser->selectedFiles();
	if(path.length()) {
		this->setDirectory(path.at(0).toStdString());
	}
}

vector<string> BrowserWidget::paths() {
	vector<string> out;

	QModelIndexList items = this->_tree->selectionModel()->selectedIndexes();
	QModelIndexList::Iterator i;

	out.clear();
	QModelIndex idx;
	for(i = items.begin(); i != items.end(); i++) {
		if(i->column() == 0) {
			idx = (*i);
			string path = "";
			do {
				if((idx.isValid())) {
					path = idx.data(0).toString().toStdString() + "/" + path;
					idx = idx.parent();
				}
			} while(idx.isValid());
			path = Utils::CleanPath(path);
			out.push_back(path);
		}
	}

	return out;
}

void BrowserWidget::setDirectory(string path) {
	this->_tree->clearSelection();

	path = Utils::CleanPath(path);
	this->_path->setText(path.c_str());

	QModelIndex idx = this->_dirModel->index(path.c_str());
	this->_tree->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect);
	do {
		this->_tree->expand(idx);
		idx = idx.parent();
	} while(idx.isValid());
}

void BrowserWidget::setGeometry(const QRect &geometry) {
	this->_tree->setGeometry(0, 0, geometry.width(), geometry.height() - 25);
	this->_path->setGeometry(0, geometry.height() - 25, geometry.width()-75, 25);
	this->_browserButton->setGeometry(geometry.width() - 75, geometry.height() - 25, 75, 25);
	this->QWidget::setGeometry(geometry);
}
